class Solution
{
public:
    bool wordPuzzle(vector<vector<char>>& grid, string target)
    {
        rows = grid.size();
        cols = grid[0].size();
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++)
                if (dfs(grid, target, i, j, 0))
                    return true;

        return false;
    }
private:
    int rows, cols;
    bool dfs(vector<vector<char>>& grid, string target, int i, int j, int k)
    {
        if (i >= rows || i < 0 || j >= cols || j < 0 || grid[i][j] != target[k])
            return false;
        if (k == target.size() - 1) return true;
        grid[i][j] = '\0';
        bool res = dfs(grid, target, i + 1, j, k + 1) ||
            dfs(grid, target, i - 1, j, k + 1) ||
            dfs(grid, target, i, j + 1, k + 1) ||
            dfs(grid, target, i, j - 1, k + 1);
        grid[i][j] = target[k];
        return res;
    }
};